package yingyong;

import gongju.DBUtil;
import packiging.Emp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/select")
public class Select extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        response.setContentType("text/html;charset=utf8");
        String sql = "select * from Emp e left join dept d on e.DeptID = d.DeptID;";
        ArrayList<Emp> list = new ArrayList<>();
        try {
            ResultSet re = DBUtil.qure(sql);
            while (re.next()){
                int EmpID = re.getInt(1);
                String EmpName = re.getString(2);
                String Sex = re.getString(3);
                int Age = re.getInt(4);
                String Tel = re.getString(5);
                String PassWord = re.getString(6);
                int DeptID = re.getInt(7);
                Emp emp = new Emp(EmpID, EmpName, Sex, Age, Tel, PassWord, DeptID);
                list.add(emp);
            }
            request.setAttribute("list",list);
            request.getRequestDispatcher("WEB-INF/list.jsp").forward(request,response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        response.setContentType("text/html;charset=utf8");
        String name = request.getParameter("user");
        if (name!=null)
        {
            String sql = "select * from Emp e left join dept d on e.DeptID = d.DeptID where EmpName like ?";

            ArrayList<Emp> list = new ArrayList<>();
            try {
                ResultSet re = DBUtil.qure(sql,"%"+name+"%");
                while (re.next()){
                    int EmpID = re.getInt(1);
                    String EmpName = re.getString(2);
                    String Sex = re.getString(3);
                    int Age = re.getInt(4);
                    String Tel = re.getString(5);
                    String PassWord = re.getString(6);
                    int DeptID = re.getInt(7);
                    Emp emp = new Emp(EmpID, EmpName, Sex, Age, Tel, PassWord, DeptID);
                    list.add(emp);
                }
                request.setAttribute("list",list);
                request.getRequestDispatcher("WEB-INF/list.jsp").forward(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
